import { Component, OnInit, ViewChild } from '@angular/core';
import { PageEntity } from '../../../core/domain/page.entity';
import { StatusEnum } from '../../../core/enum/status.enum';
import { FilterEnum, FilterTypeEnum } from '../../../core/enum/filter.enum';
import { NzMessageService } from 'ng-zorro-antd';
import { OtherUtil } from '../../../utils/other.util';
import {PostDown} from '../../../utils/postdown';
import {SystemTofileService} from './system-tofile.service';
import {PaginationUtils} from '../../../utils/paginationUtils';

declare var $: any;

@Component({
  selector: 'app-system-tofile',
  templateUrl: './system-tofile.component.html',
  styleUrls: ['./system-tofile.component.scss'],
  providers: [SystemTofileService, PostDown]
})

export class SystemTofileComponent implements OnInit {
  // 树
  pageInfo: PageEntity = new PageEntity();
  isVisible = false;
  className = '';
  dataList = [];
  isAllCheck = false;
  isIndeterminate = false;
  displayList = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  canDelete = true;
  name = null;
  number = null;

  widthConfigs = [
    '60px', '180px', '200px', '150px', '150px',
    '150px', '150px', '150px', '280px', '200px',
    '150px', '150px', '200px', '200px'
  ];
  stateObj = {
    0: '新增',
    5: '修改',
    10: '停用'
  };

  tabType: any = 'all';
  tabTypeDetail: any = 'all';

  setting = {
    data: {
      key: {
        name: 'title'
      },
      simpleData: {
        enable: true,
        idKey: 'id'
      },
      keep: {
        parent: true,
        leaf: true
      }
    },
    callback: {
      onClick: (event, treeId, treeNode) => {
        this.publishDeptId = treeNode.key;
        this.resetSearch();
      }
    },
    view: {
      showIcon: false,
    }
  };
  treeNodes: any[] = [];
  publishDeptId = null; // 当前部门id

  pageIndex = 1; // 3,反馈详情
  currObj = null;

  insId = null; // 制度id
  pageInfoDetail: PageEntity = new PageEntity();
  dataListDetail = [];
  isAllCheckDetail = false;
  isIndeterminateDetail = false;
  displayListDetail = [];
  mapOfCheckedIdDetail: { [key: string]: boolean } = {};
  canDeleteDetail = true;
  feedbackName = null;
  isFeedback = null;

  constructor(private http: SystemTofileService,
              private message: NzMessageService,
              private postDown: PostDown) {
  }

  ngOnInit() {
    this.setTree();
    this.pageInfo = new PageEntity();
    this.getPage();
  }

  /*面板切换*/
  tabsChange(e) {
    this.tabType = e;
    this.resetSearch();
  }

  queryIds(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  /**
   * 处理树节点
   */
  setTree() {
    this.http.getDeptListApi().subscribe(res => {
      const { datas , status} = res;
      if (status === StatusEnum.SUCCESS) {
        this.treeNodes = datas;
        $.fn.zTree.init($('#treeText'), this.setting, datas);
        const functionLimitList = $.fn.zTree.getZTreeObj('treeText');
        functionLimitList.expandAll(true);
      }
    });
  }

  /**
   * 分页查询
   * @param page 分页条件
   */
  getPage(): void {
    // 0:新增、5:修订、10:停用
    if (this.tabType == 'all') {
      delete this.pageInfo.filters.state;
    } else {
      this.pageInfo.filters.state = PaginationUtils.filters(this.tabType, FilterEnum.EQUALS);
    }
    if (this.publishDeptId) {
      this.pageInfo.filters.publishDeptId = PaginationUtils.filters(this.publishDeptId, FilterEnum.EQUALS);
    } else {
      delete this.pageInfo.filters.publishDeptId;
    }
    this.pageInfo.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.pageInfo.filters.publishState = PaginationUtils.filters(10, FilterEnum.EQUALS);
    this.http.page(this.pageInfo).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.dataList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }

  /**
   * 进行搜索
   */
  search(): void {
    this.pageInfo = new PageEntity();
    if (this.number) {
      this.pageInfo.filters.number = PaginationUtils.filters(this.number, FilterEnum.CONTAINS);
    } else {
      delete this.pageInfo.filters.number;
    }
    if (this.name) {
      this.pageInfo.filters.name = PaginationUtils.filters(this.name, FilterEnum.CONTAINS);
    } else {
      delete this.pageInfo.filters.name;
    }
    this.getPage();
  }

  /**
   * 点击重置
   */
  resetSearch() {
    this.number = null;
    this.name = null;
    this.pageInfo = new PageEntity();
    this.getPage();
  }

  /**
   * 当前页面展示数据改变的回调函数
   */
  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  /**
   * 单选
   */
  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.queryIds();
  }

  /**
   * 全选
   */
  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
    this.queryIds();
  }

  cancelFn(): void {
    this.canDelete = true;
    this.isAllCheck = false;
    this.mapOfCheckedId = {};
    this.isIndeterminate = false;
  }

  /**
   * 1：导出选中；2：导出当前页；3：导出全部
   */
  exportShow(num: number): void {
    const obj = {
      mode: num,
      pager: {},
      sourceIds: []
    };
    if (num === 1) {
      obj.pager = {};
      obj.sourceIds = Object.keys(this.mapOfCheckedId).filter(k => this.mapOfCheckedId[k] === true);
    } else if (num === 3) {
      obj.pager = this.pageInfo;
      obj.sourceIds = [];
    }
    this.postDown.postDownload('institution-server/institution/ins/exportExcel', obj);
  }

  // 查看
  look(data) {
    this.currObj = data;
    this.pageIndex = 2;
  }

  /*附件下载*/
  downFj(data) {
    if (data.sourceId) {
      this.postDown.postDownload('security-server/dietc/sys/source/download', {id: data.sourceId});
    } else {
      this.message.warning('无附件！');
    }
  }

  backthis(e) {
    if (e) {
      this.getPage();
    }
    this.pageIndex = 1;
  }

  // 反馈详情点击
  feedBackDetail(data) {
    this.insId = data.id;
    this.tabTypeDetail = 'all';
    this.currObj = data;
    this.pageIndex = 3;
    this.getPageDetail();
  }

  /*面板切换*/
  tabsChangeDetail(e) {
    this.tabTypeDetail = e;
    this.resetSearchDetail();
  }

  /**
   * 分页查询
   * @param page 分页条件
   */
  getPageDetail(): void {
    if (this.tabTypeDetail == 'all') {
      delete this.pageInfoDetail.filters.feedbackState;
    } else {
      this.pageInfoDetail.filters.feedbackState = PaginationUtils.filters(this.tabTypeDetail, FilterEnum.EQUALS);
    }
    this.pageInfoDetail.filters.insId = PaginationUtils.filters(this.insId, FilterEnum.EQUALS);
    this.http.pageDetail(this.pageInfoDetail).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.dataListDetail = res.datas.data;
        this.pageInfoDetail.totalRecords = res.datas.totalRecords;
      }
    });
  }

  /**
   * 进行搜索
   */
  searchDetail(): void {
    this.pageInfoDetail = new PageEntity();
    if (this.feedbackName) {
      this.pageInfoDetail.filters.feedbackUserName = PaginationUtils.filters(this.feedbackName, FilterEnum.CONTAINS);
    } else {
      delete this.pageInfoDetail.filters.feedbackUserName;
    }
    if (this.isFeedback == null) {
      delete this.pageInfoDetail.filters.isExecute;
    } else {
      this.pageInfoDetail.filters.isExecute = PaginationUtils.filters(this.isFeedback, FilterEnum.EQUALS);
    }
    this.getPageDetail();
  }

  /**
   * 点击重置
   */
  resetSearchDetail() {
    this.feedbackName = null;
    this.isFeedback = null;
    this.pageInfoDetail = new PageEntity();
    this.getPageDetail();
  }

  /**
   * 当前页面展示数据改变的回调函数
   */
  currentPageDataChangeDetail($event): void {
    this.displayListDetail = $event;
    this.refreshStatusDetail();
  }

  /**
   * 单选
   */
  refreshStatusDetail(): void {
    this.isAllCheckDetail = this.displayListDetail.every(item => this.mapOfCheckedIdDetail[item.id]);
    this.isIndeterminateDetail =
      this.displayListDetail.some(item => this.mapOfCheckedIdDetail[item.id]) &&
      !this.isAllCheckDetail;
    this.queryIds();
  }

  /**
   * 全选
   */
  checkAllDetail(value: boolean): void {
    this.displayListDetail.forEach(item => (this.mapOfCheckedIdDetail[item.id] = value));
    this.refreshStatusDetail();
    this.queryIds();
  }

  cancelFnDetail(): void {
    this.canDeleteDetail = true;
    this.isAllCheckDetail = false;
    this.mapOfCheckedIdDetail = {};
    this.isIndeterminateDetail = false;
  }

  /**
   * 1：导出选中；2：导出当前页；3：导出全部
   */
  exportShowDetail(num: number): void {
    const obj = {
      mode: num,
      pager: {},
      sourceIds: []
    };
    if (num === 1) {
      obj.pager = {};
      obj.sourceIds = Object.keys(this.mapOfCheckedIdDetail).filter(k => this.mapOfCheckedIdDetail[k] === true);
    } else if (num === 3) {
      obj.pager = this.pageInfoDetail;
      obj.sourceIds = [];
    }
    this.postDown.postDownload('institution-server/institution/feedback/exportExcel', obj);
  }

}

